package com.group4.Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonObject;
import com.group4.DB.Post;

@WebServlet(name = "DeletePost", displayName = "DeletePost", urlPatterns = { "/post/delete" })
public class DeletePost extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2300744332923628387L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		// Get the printwriter object from response to write the required json
		// object to the output stream
		
		
		String postId = request.getParameter("postId");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		
		if(postId==null  ){
			jsonObject.addProperty("error", "missing parameter!");
			out.print(jsonObject);
			out.flush();
		}else {
			boolean res = Post.deletePost(Integer.valueOf(postId));
			if(res){
				jsonObject.addProperty("success", "post deleted");
				jsonObject.addProperty("postId", postId);
				out.print(jsonObject);
				out.flush();
			}else{
				jsonObject.addProperty("error", "Error occured while deleting post!");
				out.print(jsonObject);
				out.flush();
			}
			
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String postId = request.getParameter("postId");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();
		
		if(postId==null || postId.isEmpty()  ){
			jsonObject.addProperty("error", "missing parameter!");
			out.print(jsonObject);
			out.flush();
		}else {
			boolean res = Post.deletePost(Integer.valueOf(postId));
			if(res){
				jsonObject.addProperty("success", "post deleted");
				jsonObject.addProperty("postId", postId);
				out.print(jsonObject);
				out.flush();
			}else{
				jsonObject.addProperty("error", "Error occured while deleting post!");
				out.print(jsonObject);
				out.flush();
			}
			
		}
				
	}
}
